package com.menghanjun.mhjresourcesharing.controller;


import com.alibaba.fastjson2.JSONObject;
import com.menghanjun.mhjresourcesharing.entity.TResources;
import com.menghanjun.mhjresourcesharing.service.ITResourcesService;
import com.menghanjun.mhjresourcesharing.utils.CombinedIdGenerator;
import com.menghanjun.mhjresourcesharing.utils.JsonResponseBody;
import com.menghanjun.mhjresourcesharing.utils.JsonResponseStatus;
import com.menghanjun.mhjresourcesharing.utils.Utils;
import com.menghanjun.mhjresourcesharing.vo.TResourcesVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.awt.*;
import java.io.File;
import java.util.*;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author menghanjun
 * @since 2024-04-19
 */
@RestController
@RequestMapping("/resources")
@Slf4j
public class TResourcesController {


    @Autowired
    private ITResourcesService resourcesService;


    /**
     * 增加资源
     * @param resources
     * @return
     */
    @PostMapping("/admin/addResources")
    public JsonResponseBody<?> addResources(@RequestBody TResources resources){
        try {
            if (resources.getTitle().isEmpty()||(StringUtils.isEmpty(resources.getUrl())&&(!resources.getType().equals("文案哲理")&&!resources.getType().equals("其它工具")))){//文案哲理和其它工具的url是可以为空的
                return new JsonResponseBody<>(JsonResponseStatus.LACK_PARAM);
            }
            resources.setCreatedAt(new Date());
            resources.setArchived("Y");
            resources.setClickCount(1);
            resourcesService.save(resources);
        }catch (Exception e) {
            log.error("addResources报错！"+e.getMessage());
            return new JsonResponseBody<>(JsonResponseStatus.ERORR);
        }
        return new JsonResponseBody<>();
    }




    /**
     * 根据标题和类型查询资源
     * @param type
     * @return
     */
    @GetMapping("/getResourcesList")
    public JsonResponseBody<?> getResourcesList(String type,String title,String resourceId,String level,int pageNo,
                                                int pageSize,String order,String queryFlag){
        List<TResourcesVo> resourcesList;
        int total = 0;
        try {
           resourcesList = resourcesService.getResourcesList(type,title,resourceId,level,pageNo,pageSize,order,queryFlag);
            total = resourcesService.getResourcesListTotal(type, title,resourceId,level,queryFlag);
        }catch (Exception e) {
            log.error("getResourcesList报错！"+e.getMessage());
            return new JsonResponseBody<>(JsonResponseStatus.ERORR);
        }
        return new JsonResponseBody<>(resourcesList,total);
    }





    /**
     * 根据标题和类型查询资源
     * @param resources
     * @return
     */
    @GetMapping("/getResourceUrlById")
    public JsonResponseBody<?> getResourceUrlById(TResources resources){
        String url;
        try {
            url = resourcesService.getResourceUrlById(resources.getResourceId()+"");
        }catch (Exception e) {
            log.error("getResourceUrlById报错！"+e.getMessage());
            return new JsonResponseBody<>(JsonResponseStatus.ERORR);
        }
        return new JsonResponseBody<>(url);
    }


    /**
     * 管理员根据资源Id获取资源
     * @param resourceId
     * @return
     */
    @GetMapping("/admin/getResourceById")
    public JsonResponseBody<?> adminGetResourceById(String resourceId){
        TResources resources;
        try {
            resources = resourcesService.getResourceById(resourceId);
        }catch (Exception e) {
            log.error("adminGetResourceById！"+e.getMessage());
            return new JsonResponseBody<>(JsonResponseStatus.ERORR);
        }
        return new JsonResponseBody<>(resources);
    }

    /**
     * 根据资源Id获取资源
     * @param resourceId
     * @return
     */
    @GetMapping("/getResourceById")
    public JsonResponseBody<?> getResourceVoById(String resourceId){
        TResourcesVo resources;
        try {
            resources = resourcesService.getResourceVoById(resourceId);
        }catch (Exception e) {
            log.error("getResourceVoById！"+e.getMessage());
            return new JsonResponseBody<>(JsonResponseStatus.ERORR);
        }
        return new JsonResponseBody<>(resources);
    }

    /**
     * 管理员修改资源
     * @param resources
     * @return
     */
    @PostMapping("/admin/updateResource")
    public JsonResponseBody<?> updateResource(@RequestBody TResources resources){
        try {
            if (resources.getTitle().isEmpty()||(StringUtils.isEmpty(resources.getUrl())&&(!resources.getType().equals("文案哲理")&&!resources.getType().equals("其它工具")))){//文案哲理和其它工具的url是可以为空的
                return new JsonResponseBody<>(JsonResponseStatus.LACK_PARAM);
            }
            resources.setUploaderId(null);//管理员修改资源时，不能修改上传者id
            resourcesService.updateResource(resources);
        }catch (Exception e) {
            log.error("updateResource报错！"+e.getMessage());
            return new JsonResponseBody<>(JsonResponseStatus.ERORR);
        }
        return new JsonResponseBody<>();
    }


    /**
     * 管理员删除资源
     * @param resourceId
     * @return
     */
    @GetMapping("/admin/thoroughDeleteResourceById")
    public JsonResponseBody<?> thoroughDeleteResourceById(String resourceId){
        try {
            resourcesService.thoroughDeleteResourceById(resourceId);
        }catch (Exception e) {
            log.error("thoroughDeleteResourceById报错！"+e.getMessage());
            return new JsonResponseBody<>(JsonResponseStatus.ERORR);
        }
        return new JsonResponseBody<>();
    }


    /**
     * 管理员上传资源图片
     * @param file
     * @param resourceId
     * @return
     */
    @PostMapping("/admin/uploadResourceImage")
    public JSONObject uploadResourceImage(@RequestParam("file") MultipartFile file, String resourceId){
        JSONObject json = new JSONObject();
        try {
            String imageUrl = resourcesService.uploadResourceImage(file, resourceId);
            if(imageUrl.equals("typeerr")){
                json.put("errno", 1);
                json.put("message", "非法的文件类型！");
                return json;
            }
            json.put("errno", 0);
            JSONObject data = new JSONObject();
            data.put("url", imageUrl);
            json.put("data", data);
        }catch (Exception e) {
            log.error("uploadResourceImage报错！"+e.getMessage());
            json.put("errno", 1);
            json.put("message", "上传失败");
            return json;
        }
        return json;
    }

    /**
     * 创建资源封面
     * @param resourceId 资源id
     * @param text 文字
     * @param fontType 字体类型
     * @param fontStyle 字体样式
     * @param fontSize 字体大小
     * @param fontColor  字体颜色
     * @param color 颜色
     * @param width 宽度
     * @param height 高度
     * @param tmpFlag  是否是临时文件
     * @return
     */
    @GetMapping("/admin/createResourceCover")
    public JsonResponseBody<?> createResourceCover(@RequestParam String resourceId,@RequestParam  String text,@RequestParam  String fontType,
                                                   @RequestParam  String fontStyle,@RequestParam  int fontSize,@RequestParam  String fontColor,
                                                   @RequestParam  String color,@RequestParam  int width,@RequestParam  int height,String tmpFlag){
        try {
            String projectPath = System.getProperty("user.dir"); // 获取当前项目的路径
            File projectFile = new File(projectPath); // 构建项目路径的 File 对象
            String projectDrive = projectFile.getParentFile().getAbsolutePath(); // 获取项目所在盘符的绝对路径
            if (StringUtils.isEmpty(tmpFlag)){
                tmpFlag = "N";
            }
            if(tmpFlag.equals("Y")){
                projectDrive += "/resources/tmp";
            }else{
                projectDrive += "/resources/cover/"+resourceId;
            }
            File file = new File(projectDrive);
            if (!file.exists()) {//如果没有文件夹创建文件夹
                file.mkdirs();
            }
            // 设置文件上传的路径
            String path  = projectDrive+"/"+resourceId+".png";
            Color fontColor1 = Color.decode(fontColor);
            Color color1 = Color.decode(color);
            //创建封面
            Utils.createResourceCover(text, fontType, fontStyle, fontSize,path, fontColor1, color1, width, height);
            String imageUrl = "/resourcesharing/img/cover/"+resourceId+"/"+resourceId+".png";
            if(tmpFlag.equals("Y")){
                imageUrl = "/resourcesharing/img/tmp/"+resourceId+".png";
            }
            return new JsonResponseBody<>(imageUrl);
        }catch (Exception e) {
            log.error("createResourceCover报错！"+e.getMessage());
            return new JsonResponseBody<>(JsonResponseStatus.ERORR);
        }
    }


    /**
     * 新增资源时获取一个ID
     */
    @GetMapping("/admin/getResourceId")
    public JsonResponseBody<?> getResourceId(){
        String resourceId = CombinedIdGenerator.generateId()+"";
        return new JsonResponseBody<>(resourceId);
    }

    /**
     * 判断某个资源是否存在
     * @param resourceId
     * @return
     */
    @GetMapping("/isResourceExist")
    public JsonResponseBody<?> isResourceExist(@RequestParam String resourceId){
        try {
            boolean isExist = resourcesService.isResourceExist(resourceId);
            return new JsonResponseBody<>(isExist);
        } catch (Exception e) {
            log.error("isResourceExist报错！"+e.getMessage());
            return new JsonResponseBody<>(JsonResponseStatus.ERORR);
        }
    }


    /**
     * 修改资源封面
     * @param resources
     * @return
     */
    @PostMapping("/admin/updateResourceCover")
    public JsonResponseBody<?> updateResourceCover(@RequestBody TResources resources){
        try {
            resourcesService.updateResource(resources);
        }catch (Exception e) {
            log.error("updateResourceCover报错！"+e.getMessage());
            return new JsonResponseBody<>(JsonResponseStatus.ERORR);
        }
        return new JsonResponseBody<>();
    }

    /**
     * 根据ID逻辑删除资源
     */
    @GetMapping("/admin/deleteResourceById")
    public JsonResponseBody<?> deleteResourceById(@RequestParam String resourceId){
        try {
            resourcesService.deleteResourceById(resourceId);
        }catch (Exception e) {
            log.error("deleteResourceById报错！"+e.getMessage());
            return new JsonResponseBody<>(JsonResponseStatus.ERORR);
        }
        return new JsonResponseBody<>();
    }


    /**
     * 初始化主界面
     * @return
     */
    @GetMapping("/initMainPage")
    public JsonResponseBody initMainPage(String order){
        try {
            return new JsonResponseBody<>(resourcesService.initMainPage(order));
        }catch (Exception e) {
            log.error("initMainPage报错！"+e.getMessage());
            return new JsonResponseBody<>(JsonResponseStatus.ERORR);
        }
    }


    /**
     * 上传资源封面
     * @param file
     * @param resourceId
     * @param tmpFlag
     * @return
     */
    @PostMapping("/admin/uplaodCover")
    public JsonResponseBody<?> uplaodCover(@RequestParam("file") MultipartFile file, String resourceId,String tmpFlag){
        try {
            String projectPath = System.getProperty("user.dir"); // 获取当前项目的路径
            File projectFile = new File(projectPath); // 构建项目路径的 File 对象
            String projectDrive = projectFile.getParentFile().getAbsolutePath(); // 获取项目所在盘符的绝对路径
            if (StringUtils.isEmpty(tmpFlag)){
                tmpFlag = "N";
            }
            if(tmpFlag.equals("Y")){
                projectDrive += "/resources/tmp";
            }else{
                projectDrive += "/resources/cover/"+resourceId;
            }
            File filedir = new File(projectDrive);
            if (!filedir.exists()) {//如果没有文件夹创建文件夹
                filedir.mkdirs();
            }
            // 获取文件的原始名称
            String ext = file.getOriginalFilename();
            ext = ext.substring(ext.lastIndexOf("."),ext.length());//拿到文件后缀
            if(!ext.toLowerCase().equals(".png")&&!ext.toLowerCase().equals(".jpg")&&!ext.toLowerCase().equals(".jpeg"))  {
                return new JsonResponseBody<>(JsonResponseStatus.FILE_TYPE_ERROR);
            }
            // 设置文件上传的路径
            String path  = projectDrive+"/"+resourceId+ext;
            // 以绝对路径保存重命名后的文件
            file.transferTo(new File(path));
            String imageUrl = "/resourcesharing/img/cover/"+resourceId+"/"+resourceId+ext;
            if(tmpFlag.equals("Y")){
                imageUrl = "/resourcesharing/img/tmp/"+resourceId+ext;
            }
            return new JsonResponseBody<>(imageUrl);
        }catch (Exception e) {
            log.error("uploadResourceImage报错！"+e.getMessage());
            return new JsonResponseBody<>(JsonResponseStatus.ERORR);
        }
    }


    /**
     * 增加一次点击量
     * @param resourceId
     * @return
     */
    @GetMapping("/addClikCount")
    public JsonResponseBody<?> addClikCount(@RequestParam String resourceId){
        try {
            resourcesService.addClikCount(resourceId);
        }catch (Exception e) {
            log.error("addClikCount报错！"+e.getMessage());
            return new JsonResponseBody<>(JsonResponseStatus.ERORR);
        }
        return new JsonResponseBody<>();
    }
}
